import React, { useState, useEffect } from 'react'
import './styles.less'

/**
 * 计数器
 */

// num : 默认参数
interface IComponent {
    num?: number
    max?: number
    min?: number
    onClick(num: number): void
}

const Component: React.FC<IComponent> = ({ num = 0, max = 50, min = 0, onClick }) => {
    const [number, setNumber] = useState(num)

    useEffect(() => onClick(number))

    const subtract = () => {
        if (number <= min) return;
        setNumber(number - 1)
    }
    const add = () => {
        if (number >= max) return;
        setNumber(number + 1)
    }

    return (
        <section className='c-counter'>
            <span className='c-counter-num'>{number}</span>
            <div className='c-counter-btn'>
                <span className='c-subtract' onClick={() => subtract()}>-</span>
                <span className='c-add' onClick={() => add()}>+</span>
            </div>
        </section>
    )
}

export default Component
